package com.my.swas.photo.controller;

import cn.hutool.core.io.FileUtil;
import com.baidu.aip.util.Base64Util;
import com.google.common.io.Files;
import com.my.swas.photo.config.PhotoYmlConfig;
import com.my.swas.photo.utils.BaiDuBodyAnalysisUtil;
import com.my.swas.photo.utils.BaiDuImageProcessUtil;
import com.my.swas.photo.utils.CommonUtil;
import com.my.swas.photo.utils.GoogleImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @author: :MaYong
 */
@ApiIgnore
@RestController
@Slf4j
@RequestMapping("file_build")
public class FileBuildController {

    @Resource
    PhotoYmlConfig photoYmlConfig;


    @PostMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "imageType", required = false) String imageType, HttpServletRequest request) {
        try {
            log.info("开始上传文件");
            if (file.isEmpty()) {
                return "";
            }
            int len = request.getContentLength() / 1024 / 1024;
            int a = request.getContentLength() / 1024 % 1024;
            if (len > 30) {
                return "";
            }

            log.info("文件名称：{}", file.getName());
            log.info("文件地址：{}", file.getOriginalFilename());
            log.info("文件大小：{}.{} MB", len, a);

            String now = LocalDate.now().toString().replaceAll("-","_");
            String tempdir = photoYmlConfig.getMy().getTempdir() + File.separator + now;
            File f = new File(tempdir);
            if(!f.exists()){
                f.mkdir();
            }

            String afterTransferPath = tempdir + File.separator + file.getOriginalFilename();
            File afterTransferFile = new File(afterTransferPath);
            if (!afterTransferFile.exists()) {
                afterTransferFile.getParentFile().mkdirs();
                afterTransferFile.createNewFile();
            }
            file.transferTo(afterTransferFile);
            if (StringUtils.isBlank(imageType)) {
                imageType = "5";
            }
            log.info("imageType:{}", imageType);
            log.info("保存文件地址：{}", afterTransferPath);
            File yaSuoFile = GoogleImageUtil.compression(afterTransferFile, Float.valueOf(ImgUtils._COMPRESSION_RATIO),tempdir);
            String cutPath = changeImage(yaSuoFile, imageType,tempdir);
            //log.info("剪切后文件地址：{}", cutPath);
            //BaiDuImageProcessUtil.prettifyImage(new File(cutPath));
            String segPath = BaiDuBodyAnalysisUtil.bodySeg(new File(cutPath),tempdir);
            log.info("抠图路径:{}", segPath);
            String path = "https://my.crytst.com/image/" + now + File.separator + new File(segPath).getName();
            log.info("访问路径:{}", path);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("图片制作失败：{}", e);
        }
        return "";
    }


    @GetMapping("test")
    public String test() {
        try {
            String dirPath = "D:/360安全浏览器下载/3/";
            List<String> list = FileUtil.listFileNames(dirPath);
            for (String s : list) {
                File file = new File(dirPath + s);
                String tempdir = photoYmlConfig.getMy().getTempdir() + File.separator + LocalDate.now().toString();
                tempdir = tempdir.replaceAll("-","_");
                File f = new File(tempdir);
                if(!f.exists()){
                    f.mkdir();
                }
                File yaSuoFile = GoogleImageUtil.compression(file, Float.valueOf(ImgUtils._COMPRESSION_RATIO),tempdir);
                String cutPath = changeImage(yaSuoFile, FileSizeEnum.ID_CARD.getCode(),tempdir);
                String segPath = BaiDuBodyAnalysisUtil.bodySeg(new File(cutPath),tempdir);
                log.info(segPath);
            }
            return "";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    private String changeImage(File yaSuoFile, String imageType,String tempdir) throws IOException {
        String filePath = yaSuoFile.getPath();
        JSONObject jsonObject = BaiDuBodyAnalysisUtil.bodyPointDiscern(filePath);
        if (jsonObject == null) {
            String temp = GoogleImageUtil.tempFile(yaSuoFile,tempdir);
            CommonUtil.saveImage(Base64Util.encode(CommonUtil.readFileStream(yaSuoFile)), temp);
            return temp;
        }
        JSONObject n = jsonObject.getJSONObject("nose");
        BigDecimal nose_x = n.getBigDecimal("x");
        BigDecimal nose_y = n.getBigDecimal("y");
        JSONObject leftEyeXy = jsonObject.getJSONObject("left_eye");
        JSONObject rightEyeXy = jsonObject.getJSONObject("right_eye");
        BigDecimal leftEye_x = leftEyeXy.getBigDecimal("x");
        BigDecimal rightEye_x = rightEyeXy.getBigDecimal("x");
        BigDecimal xy = leftEye_x.subtract(rightEye_x);
        BigDecimal bei = (new BigDecimal(FileSizeEnum.getBinocularSpacing(imageType)).divide(leftEye_x.subtract(rightEye_x), 4, BigDecimal.ROUND_HALF_UP));
        log.info("双眼间距和正常比：{}",bei);
        BigDecimal start = new BigDecimal(ImgUtils._VALUE_RANGE_RATIO);
        BigDecimal end = new BigDecimal(ImgUtils._VALUE_RANGE_RATIO_SMALL);

        imageType = FileSizeEnum.ID_CARD.getCode();

        if (bei.compareTo(start) >= 0 || bei.compareTo(end) < 0) {
            filePath = toCut(new File(filePath), imageType, nose_x, nose_y, bei,tempdir);
        } else {
            filePath = GoogleImageUtil.cut(yaSuoFile, nose_x, nose_y, imageType,tempdir);
        }
        return filePath;
    }

    private String toCut(File cutFile, String imageType, BigDecimal nose_x, BigDecimal nose_y, BigDecimal power,String tempdir) throws IOException {
        BigDecimal _MAGNIFICATION_POWER = Objects.isNull(power) ? new BigDecimal(ImgUtils._MAGNIFICATION_POWER) : power;
        String filePath = GoogleImageUtil.toBig(cutFile, _MAGNIFICATION_POWER,tempdir);
        BigDecimal n_nose_x = nose_x.multiply(_MAGNIFICATION_POWER);
        BigDecimal n_nose_y = nose_y.multiply(_MAGNIFICATION_POWER);
        filePath = GoogleImageUtil.cut(new File(filePath), n_nose_x, n_nose_y, imageType,tempdir);
        /*if (GoogleImageUtil.getSize(new File(filePath)) > 0.1) {
            filePath = GoogleImageUtil.compression(new File(filePath), 0.1f).getPath();
        }
        JSONObject jsonObject = BaiDuBodyAnalysisUtil.bodyPointDiscern(filePath);/String cutPath = GoogleImageUtil.cut(cutFile, jsonObject, imageType);

        JSONObject leftEyeXy = jsonObject.getJSONObject("left_eye");
        JSONObject rightEyeXy = jsonObject.getJSONObject("right_eye");
        BigDecimal leftEye_x = leftEyeXy.getBigDecimal("x");
        BigDecimal rightEye_x = rightEyeXy.getBigDecimal("x");
        BigDecimal space = leftEye_x.subtract(rightEye_x);
        log.info("双眼间距：" + space);
        BigDecimal bei = (new BigDecimal(FileSizeEnum.getBinocularSpacing(imageType)).divide(space, 4, BigDecimal.ROUND_HALF_UP));
        BigDecimal start = new BigDecimal(ImgUtils._VALUE_RANGE_RATIO);
        if (bei.compareTo(start) >= 0 || space.compareTo(new BigDecimal("50")) < 0) {
            BigDecimal n_nose_x = nose_x.multiply(_MAGNIFICATION_POWER);
            BigDecimal n_nose_y = nose_y.multiply(_MAGNIFICATION_POWER);
            filePath = toCut(new File(filePath),imageType,n_nose_x,n_nose_y,_MAGNIFICATION_POWER);
        }*/
        return filePath;
    }

}
